﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpWeb
{
    /// <summary>
    /// 容器标签
    /// </summary>
    public abstract class AbstractContainerTagComponent : TagComponent
    {
        public AbstractContainerTagComponent()
        {
            _Children = new ComponentCollection();
        }
        protected override bool CloseItSelf
        {
            get
            {
                return this.Children.Count == 0;
            }
        }

        private readonly ComponentCollection _Children;
        /// <summary>
        /// 子组件
        /// </summary>
        protected ComponentCollection Children
        {
            get { return _Children; }
        }
        /// <summary>
        /// 绘制内容，在容器组件中绘制子组件
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="context"></param>
        protected override void OnRenderContent(StringBuilder sb, ComponentContext context)
        {
            base.OnRenderContent(sb, context);
            foreach (IComponent item in Children)
            {//渲染所有子组件
                if (item is TagComponent)
                {
                    TagComponent comp = ((TagComponent)item);
                    this.OnBeforeRenderChild(comp, sb, context);
                    comp.RenderComponent(sb, context.Clone(comp));//渲染子组件
                    this.OnAfterRenderChild(comp, sb, context);
                }
            }
        }
        /// <summary>
        /// 在渲染某个子组件之前
        /// </summary>
        /// <param name="comp"></param>
        /// <param name="context">此时上下文依然为容器组件的上下文</param>
        /// <returns></returns>
        protected virtual void OnBeforeRenderChild(TagComponent beforecomp, StringBuilder sb, ComponentContext context)
        {
        }
        /// <summary>
        /// 在渲染某个子组件之后
        /// </summary>
        /// <param name="aftercomp"></param>
        /// <param name="sb"></param>
        /// <param name="context">此时上下文依然为容器组件的上下文</param>
        protected virtual void OnAfterRenderChild(TagComponent aftercomp, StringBuilder sb, ComponentContext context)
        { }
    }
}
